package ru.spb.osll.myfit.server.handler;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import ru.spb.osll.myfit.common.Content;
import ru.spb.osll.myfit.common.TreeNode;
import ru.spb.osll.myfit.server.parser.PageParserUtils;
import ru.spb.osll.myfit.util.FileHelper;

public class ContentCreator {
  private final String m_root;
  private FileHelper m_helper = new FileHelper();

  public ContentCreator(String root) {
    m_root = root;
  }

  public void setHelper(FileHelper helper) {
    m_helper = helper;
  }

  public Content createContent(String pagePath, Integer lv) {
    String fullPath = PageParserUtils.getFullPath(m_root, pagePath);

    Content content = new Content(lv);
    content.setPath(pagePath);

    Integer countLv = null;
    if (lv != null)
      countLv = 0;

    File file = m_helper.getFile(fullPath);

    TreeNode root = new TreeNode(file.getParentFile().getName());
    content.setTreeNode(root);
    if (countLv != null)
      countLv++;
    File[] files = m_helper.listFiles(file.getParentFile());
    for (File node : files)
      if (m_helper.isDirectory(node))
        setTree(root, node, lv, countLv);

    return content;
  }
  
  private void setTree(TreeNode root, File file, Integer lv, Integer countLv) {
    boolean flag = true;
    if (m_helper.isDirectory(file)) {
      if (countLv != null && lv != null) {
        if (countLv <= lv)
          countLv++;
        else
          flag = false;
      }

      String fileNames[] = m_helper.list(file);
      List<String> names = Arrays.asList(fileNames);
      if (names.contains("content.txt")) {
        root.hasChild();
        if (flag) {
          TreeNode node = new TreeNode(file.getName());
          root.addChildNode(node);
          File[] files = m_helper.listFiles(file);
          for (File fileNode : files)
            if (m_helper.isDirectory(fileNode))
              setTree(node, fileNode, lv, countLv);
        }
      }
    }
  }

}

